package com.sunni.controller.realm;

import com.sunni.entity.Employee;
import com.sunni.entity.Permission;
import com.sunni.entity.Role;
import com.sunni.service.EmployeeService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

public class EmployeeRealm extends AuthorizingRealm {

    @Autowired
    private EmployeeService employeeService;

    /*认证*/
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("来到了en认证");

//        前台 username、password自动封装成token

        /*获取 输入的用户名*/
        String username = (String) token.getPrincipal();

        /*根据前台输入的用户名，到后台查询有没有这个用户名*/
        Employee employee = employeeService.selectEmployeeByUsername(username);
        System.out.println(employee);
        if (employee == null){
            return null;
        }

        /*认证*/
        /*有的话，添加认证,并自动把用户信息添加进session*/
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(employee, employee.getPassword(),
                ByteSource.Util.bytes(employee.getUsername()),this.getName());
        return info;
    }

    /*授权*/
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

        System.out.println("进入了授权认证！！");

        /*获取当前Employee信息*/
        Employee employee = (Employee) principals.getPrimaryPrincipal();

        /*根据当前用户，，，查询对应的roles角色和permission权限信息*/
        List<String> roleList = new ArrayList<>();
        List<String> permissionList = new ArrayList<>();

        /*判断是不是管理员*/
        if (employee.getAdmin()){  /*是管理员 添加所有权限*/
                permissionList.add("*:*");
        }else { /*不是管理员  查询对应角色和权限*/
            /*查询所有role角色 （只要rname，所以List是String）*/
            roleList = employeeService.selectRoleNamesByEid(employee.getId());
            /*查询所有permission 用户权限*/
            permissionList = employeeService.selectPermissionResourcesByEid(employee.getId());
        }


        /*添加 role角色信息 和 permission权限信息*/
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addRoles(roleList);
        info.addStringPermissions(permissionList);

        return info;
    }


}
